using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PokerLearner.Poker;

namespace PokerLearner.Server
{
	public partial class FormLogger : Form
	{
		private delegate void RecordCallback(Record record);

		public FormLogger()
		{
			InitializeComponent();
			PokerLogger.Instance.RecordAdded += new EventHandler<RecordEventArgs>(PokerLogger_RecordAdded);
			PokerLogger.Instance.RecordsRead += new EventHandler(PokerLogger_RecordsRead);
		}
		
		void AddRecord(Record rec)
		{
			if (listViewRecords.InvokeRequired)
				this.Invoke(new RecordCallback(AddRecord), new object[] { rec });
			else
			{
				string preFlopPlays = "";
				if (rec.PreFlopPlays != null)
				{
					for (int i = 0; i < rec.PreFlopPlays.Count; i++)
					{
						Play play = rec.PreFlopPlays[i];
						preFlopPlays += play.ToString() + ((i < rec.PreFlopPlays.Count - 1) ? " - " : "");
					}
				}

				string flopPlays = "";
				if (rec.FlopPlays != null)
				{
					for (int i = 0; i < rec.FlopPlays.Count; i++)
					{
						Play play = rec.FlopPlays[i];
						flopPlays += play.ToString() + ((i < rec.FlopPlays.Count - 1) ? " - " : "");
					}
				}

				string turnPlays = "";
				if (rec.TurnPlays != null)
				{
					for (int i = 0; i < rec.TurnPlays.Count; i++)
					{
						Play play = rec.TurnPlays[i];
						turnPlays += play.ToString() + ((i < rec.TurnPlays.Count - 1) ? " - " : "");
					}
				}

				string riverPlays = "";
				if (rec.RiverPlays != null)
				{
					for (int i = 0; i < rec.RiverPlays.Count; i++)
					{
						Play play = rec.RiverPlays[i];
						riverPlays += play.ToString() + ((i < rec.RiverPlays.Count - 1) ? " - " : "");
					}
				}

				ListViewItem item = new ListViewItem(new string[] { rec.Identifier.ToString(), rec.PreFlopHand.ToString(), 
					preFlopPlays, 
					(rec.FlopHand != null) ? rec.FlopHand.ToString() : "",
					flopPlays,
					(rec.TurnHand != null) ? rec.TurnHand.ToString() : "",
					turnPlays,
					(rec.RiverHand != null) ? rec.RiverHand.ToString() : "",
					riverPlays,
					rec.Value.ToString() });

				listViewRecords.Items.Add(item);
			}			
		}

		void PokerLogger_RecordsRead(object sender, EventArgs e)
		{
			foreach (Record record in PokerLogger.Instance.PermanentRecords)
			{
				AddRecord(record);
			}
		}

		void PokerLogger_RecordAdded(object sender, RecordEventArgs e)
		{
			AddRecord(e.Record);
		}

		private void FormLogger_FormClosing(object sender, FormClosingEventArgs e)
		{			
			if (e.CloseReason != CloseReason.FormOwnerClosing)
			{
				e.Cancel = true;
				this.Hide();
			}
		}
	}
}